package com.cie2.janji.components;

import java.util.Date;

import org.apache.tapestry5.MarkupWriter;
import org.apache.tapestry5.annotations.BeginRender;
import org.apache.tapestry5.annotations.Parameter;
import org.apache.tapestry5.annotations.SetupRender;
import org.joda.time.DateTime;
import org.joda.time.Period;
import org.joda.time.format.PeriodFormatter;
import org.joda.time.format.PeriodFormatterBuilder;

public class JodaPeriodOutput {
	
	@Parameter(required = true)
	private Date date;
	
	@Parameter
	private String suffix = " ago";
	
	private PeriodFormatter myFormat;
	
    @SetupRender
    void initializeValue()
    {
    	
		myFormat = new PeriodFormatterBuilder()
	     .printZeroRarelyFirst()
	     .appendYears()
	     .appendSuffix(" year", " years")
	     .appendSeparator(", ")
	     .printZeroRarelyFirst()
	     .appendMonths()
	     .appendSuffix(" month", " months")
	     .appendSeparator(", ")
	     .printZeroRarelyFirst()
	     .appendWeeks()
	     .appendSuffix(" week", " weeks")
	     .appendSeparator(", ")
	     .printZeroRarelyFirst()
	     .appendDays()
	     .appendSuffix(" day", " days")	     
	     .appendSeparator(" and ")
	     .printZeroAlways()
	     .appendHours()
	     .appendSuffix(" hour", " hours")	     
	     .toFormatter();
    }

		
    @BeginRender
    void renderMessage(MarkupWriter writer)
    {
        writer.write(getFormatedDate() + suffix);
    }


	public String getFormatedDate() {
		DateTime now = new DateTime();
		DateTime createdDate = new DateTime(date);
		
		Period passedTime = new Period(createdDate, now);
		return myFormat.print(passedTime);				
	}
}
